//
// Created by Tong on 2020/10/25.
//

#include <iostream>
#include "windows.h" // sleep for memeory check

#include "GRDECLGrid.h"
#include "MeshInterpolation.h"

int main(int argc, char *argv[])
{
    if(argc<=2)
    {
        std::cout<<"At least two arguments are required!"<<std::endl;
        return 1;
    }
    if(argc>4)
    {   
        if(std::string(argv[3]) == "perf_test")
        {
            MeshInterpolation::perfTestMode_ = true;
        }
        MeshInterpolation::threadNum_ = std::stoi(argv[4]);
    }
    // 输入文件1文件名
    std::string GRDECLFile1(argv[1]);
    std::cout<<"input file:"<<GRDECLFile1<<std::endl;
    // 输入文件1构造GRDECL原始关键字数据（解析GRDECL文件）
    GRDECLRawData rawData1(GRDECLFile1,"A_porps.txt");
    // 由输入文件1的GRDECL关键字数据构造网格1
    GRDECLGrid GrdeclGrid1(rawData1);
    // 输出输入文件1的vtk可视化文件（包括两个体数据）
    GrdeclGrid1.vtkCellDataWriter("inputGRDECL.vtk",GrdeclGrid1.YoungsMod_,GrdeclGrid1.Poisson_);

    // 输入文件2文件名
    std::string GRDECLFile2(argv[2]);
    std::cout<<"input file2:"<<GRDECLFile2<<std::endl;
    // 输入文件2构造GRDECL原始关键字数据（解析GRDECL文件）
    GRDECLRawData rawData2(GRDECLFile2);
    // 由输入文件2的GRDECL关键字数据构造网格2
    GRDECLGrid GrdeclGrid2(rawData2);
    // 构造插值器
    MeshInterpolation interpolator(GrdeclGrid1.cellCenters_,GrdeclGrid2.cellCenters_);

    // 根据输入文件插值点数目初始化杨氏模量数据
    GrdeclGrid2.YoungsMod_.resize(GrdeclGrid2.nCell_);
    // 根据输入文件插值点数目初始化泊松比数据
    GrdeclGrid2.Poisson_.resize(GrdeclGrid2.nCell_);
    
    // 优化内存 清除赛题1中不必要数据
    rawData1.freeData();
    rawData2.freeData();
    GrdeclGrid1.freeData();
    GrdeclGrid2.freeData();
    interpolator.freeTree();
    system("pause for memory check");
  

    // 网格1杨氏模量插值到网格2
    interpolator.interpolateMesh1toMesh2(GrdeclGrid1.YoungsMod_,GrdeclGrid2.YoungsMod_);
    // 网格1泊松比插值到网格2
    interpolator.interpolateMesh1toMesh2(GrdeclGrid1.Poisson_,GrdeclGrid2.Poisson_);
    // 输出插值后的数据
    GrdeclGrid2.vtkCellDataWriter("outputGEDECL.vtk",GrdeclGrid2.YoungsMod_,GrdeclGrid2.Poisson_);
    // *****输出赛题要求的插值后数据********
    GrdeclGrid2.writeRequiredData("B_porps.txt");
    

    // 初始化反向插值数据：杨氏模量
    DoubleList reverseYoungs(GrdeclGrid1.nCell_);
    // 初始化反向插值数据：泊松比
    DoubleList reversePossion(GrdeclGrid1.nCell_);

    // 网格2杨氏模量反向插值到网格1
    interpolator.interpolateMesh2toMesh1(GrdeclGrid2.YoungsMod_,reverseYoungs);
    // 网格2泊松比反向插值到网格1
    interpolator.interpolateMesh2toMesh1(GrdeclGrid2.Poisson_,reversePossion);
    // 输出反向插值数据
    GrdeclGrid1.vtkCellDataWriter("reverseIpGRDECL.vtk",reverseYoungs,reversePossion);

    // 计算双向插值后的误差
    DoubleList errorYoungs = calcError(GrdeclGrid1.YoungsMod_,reverseYoungs);
    // 计算双向插值后的误差
    DoubleList errorPossion = calcError(GrdeclGrid1.Poisson_,reversePossion);

    // 输出误差可视化文件
    GrdeclGrid1.vtkCellDataWriter("reverseIpGRDECLError.vtk",errorYoungs,errorPossion);

    return 0;
}
